#include "dataprocess.h"

Q_GLOBAL_STATIC(DataProcess, dataProcess)

DataProcess::DataProcess()
{
    QString path = QDir::homePath() + "/.config/ukui/sidebarUploadMessage/";
    m_sendDataInterface = new KUploadMessage(getpid());
    m_sendDataInterface->initUploadInterface("ukui-sidebar", "sidebarData", path);

}

DataProcess::~DataProcess()
{
    if (m_sendDataInterface != nullptr) {
        delete  m_sendDataInterface;
        m_sendDataInterface = nullptr;
    }
}

DataProcess *DataProcess::getInstance()
{
    return dataProcess();
}

void DataProcess::sendData(const pointDataStruct &data)
{
    // 时区需要为东八区 时区需要为东八区 时区需要为东八区
    QString tempDateTimeStr;
    QDateTime tempDateTime = QDateTime::currentDateTime().toTimeZone(QTimeZone(8*3600));
    tempDateTimeStr= tempDateTime.toString("yyyy-MM-dd HH:mm:ss.zzz");

    int curNum = 1;
    QStringList applist = QStringList();
    QString keyValue = data.module + data.function;

    if (m_functionCount.keys().contains(keyValue)) {
        curNum = m_functionCount.value(keyValue);
        curNum ++;
    }

    m_functionCount.insert(keyValue, curNum);

    if (!data.otherFunction.isEmpty()) {
        if (m_applist.keys().contains(keyValue)) {
            applist = m_applist.value(keyValue);
        }

        applist.append(data.otherFunction.at(0));
        m_applist.insert(keyValue, applist);
    }
    m_functionCount.insert(keyValue, curNum);

    // 将需要发送的信息以json格式保存
    QJsonObject jsonObj;
    QJsonArray otherFunction = QJsonArray::fromStringList(data.otherFunction);
    jsonObj.insert("module", QJsonValue(data.module));
    jsonObj.insert("function", QJsonValue(data.function));
    jsonObj.insert("functionNum", QJsonValue(QString::number(curNum)));
    jsonObj.insert("otherFunction", otherFunction);
    jsonObj.insert("errorLevel", QJsonValue(data.errorLevel));
    jsonObj.insert("errorOutput", QJsonValue(data.errorOutput));
    jsonObj.insert("createTimeStamp", tempDateTimeStr);

    //  将数据转化为QString
    QString informationData(QJsonDocument(jsonObj).toJson(QJsonDocument::Compact));
    //        qDebug()<<"调试打印数据:"<<jsonObj;
    m_sendDataInterface->UploadMessage(informationData);

}
